#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"

void SLInit(SL* pa)
{
	assert(pa);
	pa->a =(SLDateType*)malloc(sizeof(SLDateType)*4);
	if (pa->a == NULL)
	{
		perror("malloc failed");
		exit(-1);//程序结束，负数异常结束
	}
	pa->size = 0;
	pa->capacity = 4;
}

void SLDestroty(SL* pa)
{
	assert(pa);

	free(pa->a);
	pa->a = NULL;
	pa->capacity = pa->size = 0;
}
void SLPrint(SL* pa)
{
	assert(pa);

	int i = 0;
	for (i = 0; i < pa->size; i++)
	{
		printf("%d ", pa->a[i]);
	}
	printf("\n");
}

void SLCheckCapacity(SL* pa)
{
	assert(pa);

	if (pa->size == pa->capacity)
	{
		SLDateType* tmp = realloc(pa->a, pa->capacity * sizeof(SLDateType) * 2);
		if (*tmp == NULL)
		{
			perror("realloc failed");
			exit(-1);
		}
		pa->a = tmp;
		pa->capacity *= 2;
	}
}
void SLPushBack(SL* pa, SLDateType n)
{
	assert(pa);

	//SLCheckCapacity(pa);
	//pa->a[pa->size] = n;
	//pa->size++;
	SLInsert(pa, pa->size, n);
}

void SLPopBack(SL* pa)
{
	assert(pa);

	//温柔的检查
	//if (pa->a[pa->size] == 0)
	//{
	//	return 0;
	//}
	assert(pa->size>0);
	pa->size--;
}
void SLPushFront(SL* pa, SLDateType n)
{
	assert(pa);

	SLCheckCapacity(pa);
	//int end = pa->size-1;
	//while (end>=0)
	//{
	//	pa->a[end + 1] = pa->a[end];
	//	end--;
	//}
	//pa->a[0] = n;
	//pa->size++;
	SLInsert(pa, 0, n);

}
void SLPopFront(SL* pa)
{
	assert(pa);

	assert(pa->size > 0);
	for (int i = 0; i < pa->size-1; i++)//-1防止越界
	{
		pa->a[i] = pa->a[i + 1];
	}
	pa->size--;
}

int SLFind(SL* pa, SLDateType n)
{
	assert(pa);

	int i = 0;
	for (i = 0; i < pa->size; i++)
	{
		if (pa->a[i] == n)
		{
			return i;
		}
	}
	return -1;
}

void SLInsert(SL* pa, int pos, SLDateType n)
{
	assert(pa);

	assert(pos >= 0 && pos <= pa->size);//等于size相当于尾插
	SLCheckCapacity(pa);
	int end = pa->size-1;
	while (end>=pos)
	{
		pa->a[end+1] = pa->a[end];
		end--;
	}
	pa->a[pos] = n;
	pa->size++;
}
void SLErase(SL* pa, int pos)
{
	assert(pa);

	assert(pos >= 0 && pos < pa->size);//不能等于size，若等于则删除0
	int i =pos+1;
	while (i<pa->size)
	{
		pa->a[i-1] = pa->a[i];
		i++;
	}
	pa->size--;

}
void SLModify(SL* pa, int pos,int n)
{
	assert(pa);

	assert(pos >= 0 && pos <= pa->size);
	pa->a[pos] = n;
}
